<template>
  <div class="add-exam-component-box">
    <div class="add-exam-component">
      <!-- 竞赛信息模块 -->
      <div class="exam-base-info-box">
        <!-- 标题 -->
        <div class="exam-base-title">
          <span class="base-title">
            {{ type === 'edit' ? '编辑竞赛' : '添加竞赛' }}
          </span>
          <span class="go-back" @click="goBack">返回</span>
        </div>
        <!-- 基本信息 -->
        <div class="exam-base-info">
          <div class="group-box">
            <div class="group-item">
              <div class="item-label required">竞赛名称</div>
              <div>
                <el-input
                  v-model="formExam.title"
                  style="width: 420px; height: 40px"
                  placeholder="请填写竞赛名称"
                ></el-input>
              </div>
            </div>
          </div>
          <div class="group-box">
            <div class="group-item">
              <div class="item-label required">竞赛周期</div>
              <div>
                <el-date-picker
                  v-model="datetimeRange"
                  type="datetimerange"
                  start-placeholder="竞赛开始时间"
                  end-placeholder="竞赛结束时间"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format=""
                  style="width: 420px; height: 40px"
                />
              </div>
            </div>
          </div>
          <div class="group-box">
            <div class="group-item">
              <el-button
                class="exam-base-info-button"
                type="primary"
                plain
                @click="saveBaseInfo"
                style="width: 420px; height: 40px"
              >
                保存
              </el-button>
            </div>
          </div>
        </div>
      </div>
      <!-- 添加竞赛题目 -->
      <div class="exam-select-question-box">
        <el-button
          class="exam-add-question"
          :icon="Plus"
          type="text"
          @click="addQuestion()"
        >
          添加题目
        </el-button>
        <el-table
          height="250px"
          :data="formExam.examQuestionList"
          class="question-select-list"
          :header-cell-style="{
            textAlign: 'center',
            background: '#f5f7fa'
          }"
          :cell-style="{ textAlign: 'center' }"
        >
          <el-table-column
            prop="questionId"
            width="180px"
            label="题目id"
          />
          <el-table-column
            prop="title"
            :show-overflow-tooltip="true"
            label="题目标题"
          />
          <el-table-column
            prop="difficulty"
            width="80px"
            label="题目难度"
          >
            <template #default="{ row }">
              <div v-if="row.difficulty === 1" style="color: #3ec8ff">
                简单
              </div>
              <div v-if="row.difficulty === 2" style="color: #fe7909">
                中等
              </div>
              <div v-if="row.difficulty === 3" style="color: #fd4c40">
                困难
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80px">
            <template #default="{ row }">
              <el-button
                circle
                type="text"
                @click="
                  deleteExamQuestion(formExam.examId, row.questionId)
                "
                class="delete-btn"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 题目配置模块 题目列表勾选加序号 -->
      <div>
        <el-dialog
          v-model="dialogVisible"
          class="exam-question-dialog"
        >
          <div class="exam-list-box">
            <div class="exam-list-title required">选择竞赛题目</div>
            <el-form :inline="true">
              <el-form-item label="题目难度">
                <selector
                  v-model="questionQuery.difficulty"
                  style="width: 120px"
                ></selector>
              </el-form-item>
              <el-form-item label="题目名称">
                <el-input
                  v-model="questionQuery.title"
                  placeholder="请您输入要搜索的题目标题"
                />
              </el-form-item>
              <el-form-item>
                <el-button @click="onSearch" plain>搜索</el-button>
                <el-button @click="onReset" plain type="info">
                  重置
                </el-button>
              </el-form-item>
            </el-form>
            <!-- 题目列表 -->
            <el-table
              :data="questionList"
              @select="handleRowSelect"
              @select-all="handleSelectAll"
            >
              <el-table-column type="selection"></el-table-column>
              <el-table-column prop="questionId" label="题目id" />
              <el-table-column prop="title" label="题目标题" />
              <el-table-column prop="difficulty" label="题目难度">
                <template #default="{ row }">
                  <div
                    v-if="row.difficulty === 1"
                    style="color: #3ec8ff"
                  >
                    简单
                  </div>
                  <div
                    v-if="row.difficulty === 2"
                    style="color: #fe7909"
                  >
                    中等
                  </div>
                  <div
                    v-if="row.difficulty === 3"
                    style="color: #fd4c40"
                  >
                    困难
                  </div>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页区域 -->
            <div class="exam-question-list-button">
              <div class="pagination-wrapper">
                <el-pagination
                  background
                  size="small"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="total"
                  v-model:current-page="questionQuery.pageNo"
                  v-model:page-size="questionQuery.pageSize"
                  :page-sizes="[1, 5, 10, 15, 20]"
                  @size-change="getQuestionList"
                  @current-change="getQuestionList"
                  class="centered-pagination"
                />
              </div>
              <el-button
                class="question-select-submit"
                type="primary"
                plain
                @click="submitSelectQuestion"
              >
                提交
              </el-button>
            </div>
          </div>
        </el-dialog>
      </div>

      <!-- 提交任务区域 -->
      <div class="submit-box absolute">
        <el-button type="info" plain @click="goBack">取消</el-button>
        <el-button type="primary" plain @click="publishExam">
          发布竞赛
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
  import {
    examAddApi,
    addExamQuestionApi,
    getExamDetailApi,
    editExamApi,
    delExamQuestionApi,
    publishExamApi
  } from '@/api/exam'
  import { getQuestionListApi } from '@/api/question'
  import Selector from '@/views/question/components/QuestionSelector.vue'
  import router from '@/router'
  import { reactive, ref } from 'vue'
  import { Plus } from '@element-plus/icons-vue'
  import { useRoute } from 'vue-router'
  import { ElMessage } from 'element-plus'

  const type = useRoute().query.type
  // 竞赛表单响应式对象
  const formExam = reactive({
    examId: '',
    title: '',
    startTime: '',
    endTime: ''
  })
  // 题目列表响应式对象
  const questionQuery = reactive({
    pageNo: 1,
    pageSize: 5,
    difficulty: '',
    title: ''
  })
  // 日期时间范围响应式数据
  const datetimeRange = ref([])
  // 返回
  function goBack() {
    router.go(-1)
  }
  // 保存竞赛基本信息
  async function saveBaseInfo() {
    // 获取开始时间
    if (datetimeRange.value[0] instanceof Date) {
      formExam.startTime = formatDateTime(datetimeRange.value[0])
    }
    // 获取结束时间
    if (datetimeRange.value[1] instanceof Date) {
      formExam.endTime = formatDateTime(datetimeRange.value[1])
    }
    if (formExam.examId) {
      //编辑
      await editExamApi(formExam)
    } else {
      // 新增
      const resp = await examAddApi(formExam)
      formExam.examId = resp
    }
    ElMessage.success('基本信息保存成功')
  }
  //日期时间格式化
  function formatDateTime(date) {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  }
  // 查询的题目列表
  const questionList = ref([])
  // 记录总数
  const total = ref(0)
  // 获取题库
  async function getQuestionList() {
    const result = await getQuestionListApi(questionQuery)
    questionList.value = result.list
    total.value = result.totals
  }
  // 添加题目的题库对话框显示的响应式数据
  const dialogVisible = ref(false)
  // 添加竞赛题目
  function addQuestion() {
    if (formExam.examId === null || formExam.examId === '') {
      ElMessage.error('请先保存竞赛基本信息')
    } else {
      getQuestionList()
      dialogVisible.value = true
    }
  }

  // 搜索题目
  function onSearch() {
    if (questionQuery.difficulty || questionQuery.title) {
      getQuestionList()
    }
  }
  // 重置题目表单
  function onReset() {
    if (questionQuery.difficulty || questionQuery.title) {
      questionQuery.difficulty = questionQuery.title = ''
      getQuestionList()
    }
  }
  // 发布竞赛
  async function publishExam() {
    await publishExamApi(formExam.examId)
    router.push('/exam')
  }
  // 竞赛的题目id列表
  const questionIdSet = ref([])
  // 手动选择某一行题目时触发添加题目id列表（包括勾选和取消勾选）使用@select监听
  function handleRowSelect(selection) {
    updateQuestionIdSet(selection)
  }

  // 全选或取消全选时触发添加题目id列表（全选和单选使用不同的事件监听器）使用@select-all监听
  function handleSelectAll(selection) {
    updateQuestionIdSet(selection)
  }
  // 题目id列表元素的添加
  function updateQuestionIdSet(selection) {
    questionIdSet.value = Array.from(
      new Set(selection.map((item) => item.questionId))
    )
  }
  // 提交添加竞赛题目id列表请求
  async function submitSelectQuestion() {
    if (questionIdSet.value && questionIdSet.value.length < 1) {
      ElMessage.error('请先选择要提交的题目')
      return false
    }
    const examQ = reactive({
      examId: formExam.examId,
      questionIdSet: questionIdSet.value
    })
    await addExamQuestionApi(examQ)
    getExamDetailById(formExam.examId)
    dialogVisible.value = false
    ElMessage.success('竞赛题目添加成功')
  }

  // 根据URL查询参数examId获取竞赛详细信息
  async function getExamDetail() {
    const examId = useRoute().query.examId
    if (examId) {
      formExam.examId = examId
      getExamDetailById(examId)
    }
  }
  getExamDetail()
  // 删除竞赛题目
  async function deleteExamQuestion(examId, questionId) {
    await delExamQuestionApi(examId, questionId)
    getExamDetailById(examId)
    ElMessage.success('竞赛题目删除成功')
  }
  // 请求后端接口获取竞赛详细信息
  async function getExamDetailById(examId) {
    const examDetail = await getExamDetailApi(examId)
    formExam.examQuestionList = []
    // 更新表单数据
    Object.assign(formExam, examDetail)
    datetimeRange.value = [formExam.startTime, formExam.endTime]
  }
</script>

<style lang="scss" scoped>
  .add-exam-component-box {
    height: 100%;
    overflow: hidden;
    position: relative;
  }

  .exam-list-box {
    background: #fff;
    padding: 20px 24px;

    .question-select-submit {
      margin-left: 0;
      margin-top: 20px;
      width: 100%;
    }

    .exam-list-title {
      font-size: 14px;
      color: rgba(0, 0, 0, 0.85);
      position: relative;
      padding: 15px 20px;
      padding-top: 0;

      &.required::before {
        position: absolute;
        content: '*';
        font-size: 20px;
        color: red;
        left: 10px;
      }
    }
  }

  .add-exam-component {
    width: 100%;
    background: #fff;
    padding-bottom: 140px;
    overflow-y: auto;
    box-sizing: border-box;
    height: calc(100vh - 50px);
    margin-top: -10px;

    .exam-select-question-box {
      background: #fff;
      border-bottom: 1px solid #fff;
      border-radius: 2px;
      width: 100%;

      .exam-add-question {
        font-size: 14px;
        float: right;
        margin: 10px 20px 5px 0;
      }

      .question-select-list {
        margin: 0 20px 20px 20px;
        height: 250px;
        padding-right: 10px;

        :deep(.el-table__cell) {
          .delete-btn {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 100%;
            height: 100%;
            margin: 0;

            .el-button__inner {
              display: flex;
              align-items: center;
              justify-content: center;
            }
          }
        }
      }
    }

    .exam-base-info-box {
      background: #fff;
      border-bottom: 1px solid #fff;
      border-radius: 2px;
      margin-bottom: 10px;
      width: 100%;
      box-sizing: border-box;

      .exam-base-title {
        width: 100%;
        box-sizing: border-box;
        height: 52px;
        border-bottom: 1px solid #e9e9e9;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 24px;

        .base-title {
          font-size: 16px;
          font-weight: 500;
          color: #333333;
        }

        .go-back {
          color: #999;
          cursor: pointer;
        }
      }

      .exam-base-info {
        box-sizing: border-box;
        border-bottom: 1px solid #e9e9e9;
      }

      .mesage-list-content {
        box-shadow: 0px 0px 6px 0px rgba(0, 0, 0, 0.1);
        background-color: rgba(255, 255, 255, 1);
        border-radius: 10px;
        width: 1200px;
        margin-top: 20px;
      }
    }

    .group-box {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: calc(100% - 64px);
      margin: 24px 32px;

      .group-item {
        display: flex;
        align-items: center;
        width: 100%;

        .exam-base-info-button {
          margin-left: 104px;
          width: 420px;
          height: 40px;
        }

        .item-label {
          font-size: 14px;
          font-weight: 400;
          width: 94px;
          text-align: left;
          color: rgba(0, 0, 0, 0.85);
          position: relative;
          padding-left: 10px;

          &.required::before {
            position: absolute;
            content: '*';
            font-size: 20px;
            color: red;
            left: 0px;
            top: -2px;
          }
        }

        .el-input,
        .el-date-editor {
          height: 40px;
        }

        .el-button {
          height: 40px;
          line-height: 40px;
        }
      }
    }

    .submit-box {
      display: flex;
      align-items: center;
      justify-content: center;
      background: transparent;

      &.absolute {
        position: absolute;
        width: calc(100% - 48px);
        bottom: 20px;
        background: #fff;
        z-index: 999;
        padding: 0 24px;
        box-sizing: border-box;

        .el-button {
          margin: 0 10px;
        }
      }
    }
  }

  .exam-question-dialog {
    .el-dialog__body {
      padding: 20px 24px;
    }
  }
  .pagination-wrapper {
    width: 100%;
    overflow-x: auto;
    white-space: nowrap;
    margin-bottom: 15px;
    -ms-overflow-style: none;
    scrollbar-width: none;

    &::-webkit-scrollbar {
      display: none;
    }

    .el-pagination {
      display: inline-flex;
      min-width: max-content;
      font-size: 12px;
    }
  }
</style>

<style>
  .w-e-text-container {
    min-height: 142px;
  }

  .el-table .cell {
    text-align: center;
  }

  .question-select-list .el-table__cell .cell {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
  }

  .question-select-list .delete-btn {
    margin: 0 !important;
  }

  .question-select-list .el-table__body-wrapper {
    overflow-x: hidden;
  }

  .exam-question-list-button {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-top: 20px;
  }

  .centered-pagination {
    display: flex !important;
    justify-content: center !important;
    width: 100%;
    margin-bottom: 15px;
  }

  .exam-question-list-button .el-button {
    align-self: stretch;
  }
  .el-dialog {
    width: 870px;
    padding: 30px 0;
    .el-dialog__header {
      padding-bottom: 24px;
      font-size: 16px;
      font-weight: 600;
    }
  }
</style>
